package cn.yunsenlin.formula.cloud.functions;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDecimal;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.math.BigDecimal;
import java.util.Map;

public class MathRoundFunction extends AbstractFunction {
    @Override
    public String getName() {
        return "math.round";
    }

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        Number number = FunctionUtils.getNumberValue(arg1, env);
        Number b = FunctionUtils.getNumberValue(arg2, env);
        BigDecimal result = new BigDecimal(number.doubleValue());
        BigDecimal r = result.setScale(b.intValue(),BigDecimal.ROUND_HALF_UP);
        return new AviatorDecimal(r);
    }
}
